<template>
  <div>
    <div class="search_box search_head" style="margin-bottom: 18px">
      <el-radio-group
        v-model="formData.type"
        @change="handleGroup(formData.type)"
      >
        <el-radio-button :label="1">汇 总</el-radio-button>
        <el-radio-button :label="2">区分小程序</el-radio-button>
      </el-radio-group>
      <selectMultiple
        v-if="formData.type === 2"
        style="margin-left: 18px"
        ref="multAppsSelectRef"
        @selectChange="selectAppsChange"
        :placehText="'小程序'"
        :options="appsOptions"
      />
    </div>
    <div class="search_box">
      <el-form
        :inline="true"
        ref="ruleFormRef"
        :model="formData"
        :label-width="75"
      >
        <el-form-item label="报告时间">
          <selectDate ref="dateRef" type="daterange" @returnTime="returnTime" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="getList(1)"
            v-auth="'api:agent:report:summaryList'"
          >
            查 询
          </el-button>
          <el-button @click="resetList" v-auth="'api:agent:report:summaryList'">
            重 置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table_box_wrapper">
      <el-button
        type="primary"
        class="export_box"
        @click="getList(9)"
        :loading="loadingExport"
      >
        数据导出
      </el-button>
      <custom-table
        ref="tableRef"
        :loading="loading"
        :columns="columns"
        :tableData="tableData"
        :pageObj="pageObj"
        @sizechange="sizechange"
        @currentChange="currentChange"
        class="table_box"
      >
        <template #date="{ scope }">
          <span v-if="scope.row?.date">
            {{ moment(scope.row?.date + "Z").format("YYYY-MM-DD") }}
          </span>
        </template>
        <template #miniApp="{ scope }">
          <span v-if="scope.row?.miniApp">{{
            scope.row?.miniApp.appName
          }}</span>
        </template>
      </custom-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import customTable from "@/components/CustomTable/index.vue";
import { getsummaryList } from "@/api/chart/index";
import { getAppList } from "@/api/globalManage/appletRoute/index";
import { getAppsList } from "@/api/auth/index";
import selectDate from "@/components/SeleteDate/index.vue";
import moment from "moment";
import { exportTable } from "@/utils/tools";

const dateRef = ref();
const tableRef = ref();
let startT: number = new Date().getTime() - 3600000 * 24 * 6;
const loading = ref<boolean>(false);
const form = reactive({
  type: 1,
  pageNo: 1,
  pageSize: 10,
  start: moment(startT).startOf("day").format("YYYY-MM-DDTHH:mm:ss"),
  end: moment().startOf("day").format("YYYY-MM-DDTHH:mm:ss"),
  operaIds: [],
  miniAppIds: [],
});
const formData = ref(Object.assign({}, form));
const valueTime = ref<any>("");
const tableData = ref<Array<any>>([]);
const appsOptions = ref<Array<any>>([]);
const multSelectRef = ref();
const multAppsSelectRef = ref();
const loadingExport = ref(false);

interface modelPage {
  pageNo: number;
  pageSize: number;
  total: number;
}
const pageObj = reactive<modelPage>({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

const columns = reactive([
  { label: "报告日期", prop: "date", slotName: "date", minWidth: 100 },
  { label: "小程序Id", prop: "miniAppId", minWidth: 80, hidden: true },
  {
    label: "小程序名称",
    prop: "miniApp",
    slotName: "miniApp",
    minWidth: 110,
    hidden: true,
  },
  { label: "日活跃用户数", prop: "activeUsers", minWidth: 110 },
  { label: "新增用户数", prop: "newUsers", minWidth: 100 },
  { label: "充值成功次数 ", prop: "rechargeTimes", minWidth: 110 },
  { label: "充值成功人数", prop: "rechargeUsers", minWidth: 110 },
  {
    label: "充值金额(元)",
    prop: "rechargeAmount",
    minWidth: 118,
    formatter: (row: any) => {
      return `¥${row?.rechargeAmount}`;
    },
  },
  { label: "新增用户充值人数", prop: "rechargeNewUsers", minWidth: 136 },
  {
    label: "新增用户充值金额(元)",
    prop: "newUsersRechargeAmount",
    minWidth: 160,
    formatter: (row: any) => {
      return `¥${row?.newUsersRechargeAmount}`;
    },
  },
  {
    label: "新增用户付费率",
    prop: "newUsersRechargeRate",
    minWidth: 134,
    formatter: (row: any) => {
      return `${row?.newUsersRechargeRate}%`;
    },
  },
]);

// 切换汇总 / 小程序
const handleGroup = (val: number | string) => {
  tableRef.value.columnsData = columns.map((item: any) => {
    // 根据type（1 、 2）类型，显示影藏列
    if (val === 1 && (item.prop === "miniAppId" || item.prop === "miniApp")) {
      item.hidden = true;
    } else {
      item.hidden = false;
    }
    return item;
  });
  getList(1);
};

// 切换小程序
const selectAppsChange = (val: any) => {
  formData.value.miniAppIds = val;
};

// 重置
const resetList = () => {
  // form.type = formData.value.type;
  // form.miniAppIds = formData.value.miniAppIds;
  formData.value = Object.assign(formData.value, form);
  // 重置组件多选
  if (formData.value.type == 2) {
    multAppsSelectRef.value.multipleData = [];
  }
  multSelectRef.value.multipleData = [];
  dateRef.value.dateValue = [form.start, form.end];
  getList(1);
};

const getList = (val = 0) => {
  // if (!val) {
  //   formData.value.pageNo = pageObj.pageNo;
  //   formData.value.pageSize = pageObj.pageSize;
  // } else {
  //   formData.value.pageNo = pageObj.pageNo = val === 1 ? val : 1;
  //   formData.value.pageSize = pageObj.pageSize =
  //     val === 1 ? 10 : pageObj.pageSize;
  // }
  formData.value.pageNo = val && val === 9 ? 1 : pageObj.pageNo;
  formData.value.pageSize = val && val === 9 ? 100000 : pageObj.pageSize;

  // 数据导出不刷新列表
  if (val !== 9) {
    loading.value = true;
  } else {
    loadingExport.value = true;
  }
  getsummaryList(formData.value)
    .then((res: Record<string, any>) => {
      // 数据导出 中断后续数据渲染
      if (val === 9) {
        exportTable(res?.data, columns, "数据汇总");
        loadingExport.value = false;
        return;
      }

      tableData.value = res.data;
      pageObj.total = Number(res?.total);
      loading.value = true;
    })
    .finally(() => {
      loading.value = false;
    });
};

const currentChange = (val: number) => {
  pageObj.pageNo = val;
  getList();
};

const sizechange = (val: number) => {
  pageObj.pageSize = val;
  getList(2);
};

// 获取小程序
const getApps = () => {
  getAppsList().then((res: any) => {
    appsOptions.value = res.map((item: Record<string, any>) => {
      return {
        label: item.appName,
        value: item?.id.toString(),
        appType: item?.appType,
      };
    });
  });
  // getAppList({ pageNo: 1, pageSize: 1000 }).then((res: Record<string, any>) => {
  //   appsOptions.value = res.data.map((res: Record<string, any>) => {
  //     return {
  //       label: res.appName,
  //       value: res?.id.toString(),
  //     };
  //   });
  // });
};

// 返回时间
const returnTime = (val: any) => {
  valueTime.value = val;
  formData.value.start = valueTime.value[0];
  formData.value.end = valueTime.value[1];
};

onMounted(() => {
  getList();
  getApps();
});
</script>

<style lang="scss" scoped>
.search_head {
  display: flex;
  align-items: center;
}

.table_box_wrapper {
  margin-top: 15px;
  background-color: #fff;
  border-radius: 4px;

  .export_box {
    margin: 10px 0 0 10px;
  }
}

.table_box {
  padding: 10px;
  border-radius: 4px;

  .movie_box {
    display: flex;
    align-items: center;

    img {
      width: 72px;
      height: 108px;
      margin-right: 8px;
    }

    span {
      flex: 1;
    }
  }
}
</style>
